package com.personal.gateway.aop;

import com.personal.gateway.constant.LoginUserInfoConstant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @program: FlinkGateway
 * @description: webUI登录拦截使用
 * @author: yangliao
 * @create: 2021-08-20
 */
@Aspect
@Component
public class WebLoginAspect {

    @Resource
    private LoginUserInfoConstant loginUserInfoConstant;

    @Pointcut("execution(public * com.personal.gateway.web..*.*(..))")
    public void webLogin() {
    }

    @Around("webLogin()")
    public Object trackInfo(ProceedingJoinPoint pjp) throws Throwable {
        if (pjp.getSignature().getName().equals(LoginUserInfoConstant.LOGIN) ||
                pjp.getSignature().getName().equals(LoginUserInfoConstant.CAPTCHA)) {
            return pjp.proceed();
        }

        // 判断是否登录
        boolean isLogin = false;
        for (Object arg : pjp.getArgs()) {
            if (arg instanceof ServerHttpRequest) {
                ServerHttpRequest request = (ServerHttpRequest) arg;
                for (Map.Entry<String, List<HttpCookie>> entry : request.getCookies().entrySet()) {
                    if (entry.getKey().equals(LoginUserInfoConstant.TOKEN)) {
                        if (!CollectionUtils.isEmpty(entry.getValue())) {
                            for (HttpCookie cookie : entry.getValue()) {
                                if (cookie.getName().equals(LoginUserInfoConstant.TOKEN)) {
                                    String token = cookie.getValue();
                                    // 校验token是否有效 如果有效 进入系统
                                    if (loginUserInfoConstant.checkToken(token)){
                                        isLogin = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (isLogin) {
            return pjp.proceed();
        }

        return "login";
    }

}
